package com.lpb.spring.test1.factory.support;

import com.lpb.spring.test1.factory.config.BeanDefinition;
import com.lpb.spring.test1.factory.support.classinit.InstantiationStrategy;
import com.lpb.spring.test1.factory.support.classinit.JDKInstantiationStrategy;

import java.lang.reflect.Constructor;

/**
 * @author linpengbo
 * @date 2022/4/27
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStrategy instantiationStrategy=new JDKInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition definition,Object[] args) {
        Object bean=null;
        try {
            //通过bean定义初始化bean
            bean = createBeanInstance(definition,args);
        } catch (Exception e) {
       throw new RuntimeException(e.getMessage());
        }
        //默认单例-放到单例缓存里
        addSingletonBean(beanName,bean);
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition definition,Object[] args){
        Constructor ctt=null;
        Class<?> clazz = definition.getClazz();
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor ct:declaredConstructors) {
             if(args!=null&&args.length==ct.getParameterTypes().length){
                     ctt=ct;
                     break;
             }
        }
        return instantiationStrategy.initinstance(definition,ctt,args);
    }
}
